package com.eqdd.yiqidian.box.span;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.text.style.ClickableSpan;
import android.text.style.ReplacementSpan;
import android.text.style.UpdateLayout;
import android.view.View;

/**
 * @author吕志豪 .
 * @date 17-12-7  上午9:09.
 * Github :https://github.com/lvzhihao100
 * E-Mail：1030753080@qq.com
 * 简书 :http://www.jianshu.com/u/6e525b929aac
 */

public class TagSpan extends ReplacementSpan {
    private int mSize;
    private int mColor;
    private int mRadius;
    private int mSpace;
    private int lenth = 0;
    private CharSequence text;
    private TextClick textClick;

    /**
     * @param color  背景颜色
     * @param radius 圆角半径
     */
    public TagSpan(int color, int radius, int space) {
        mColor = color;
        mRadius = radius;
        mSpace = space;
    }

    @Override
    public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
        mSize = (int) (paint.measureText(text, start, end) + 2 * mRadius + 2 * mSpace);
        //mSize就是span的宽度，span有多宽，开发者可以在这里随便定义规则
        //我的规则：这里text传入的是SpannableString，start，end对应setSpan方法相关参数
        //可以根据传入起始截至位置获得截取文字的宽度，最后加上左右两个圆角的半径得到span宽度
        this.text=  text.subSequence(start,end);
        return mSize;
    }
    public int getSize(){
        return mSize;
    }

    @Override
    public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
        int color = paint.getColor();//保存文字颜色
        paint.setColor(mColor);//设置背景颜色
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(6);
        paint.setAntiAlias(true);// 设置画笔的锯齿效果
        RectF oval = new RectF(x + mSpace, y + paint.ascent(), x + mSize - mSpace, y + paint.descent());
        //设置文字背景矩形，x为span其实左上角相对整个TextView的x值，y为span左上角相对整个View的y值。paint.ascent()获得文字上边缘，paint.descent()获得文字下边缘
        canvas.drawRoundRect(oval, mRadius, mRadius, paint);//绘制圆角矩形，第二个参数是x半径，第三个参数是y半径
        paint.setColor(color);//恢复画笔的文字颜色
        paint.setStrokeWidth(1);
        paint.setStyle(Paint.Style.FILL_AND_STROKE);
        canvas.drawText(text, start, end, x + mRadius + mSpace, y, paint);//绘制文字
        this.lenth = text.length();
    }

    public int length() {
        return lenth;
    }

    public void onClick(View v) {
        if (textClick != null) {
            textClick.click(text);
        }
    }

    public void setTextClick(TextClick textClick) {
        this.textClick = textClick;
    }

    public interface TextClick{
        void click(CharSequence text);
    }
}
